<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

      <div style="margin-top: 15px;">
      <el-input placeholder="请输入内容" v-model="searchInput" class="input-with-select">
      <el-select class="selectType" v-model="select" slot="prepend" placeholder="请选择">
      <el-option label="姓名" value="username"></el-option>
      <el-option label="登录名" value="loginName"></el-option>
      <el-option label="部门" value="deptName"></el-option>
    </el-select>
    <el-button slot="append"  icon="el-icon-search" @click="searchBtn()">搜 索</el-button>
    </el-input>
       <el-button v-if="this.actions.includes('1')" type="primary" icon="el-icon-circle-plus" @click="addUser()">添 加</el-button>
    </div>
    <el-card>
      <el-table :data="this.userList.data" border stripe >
        <el-table-column type="index" align="center"></el-table-column>
        <el-table-column label="姓名" prop="username" align="center"></el-table-column>
        <el-table-column label="登录名" prop="loginName" align="center"></el-table-column>
        <el-table-column label="邮箱" prop="email" align="center"></el-table-column>
        <el-table-column label="电话" prop="mobile" align="center"></el-table-column>
        <el-table-column label="部门" prop="deptName" align="center"></el-table-column>
        <el-table-column label="角色" align="center">
          <template slot-scope='scope'>
            {{ scope.row.remark }}
            <el-tag type="success" v-if="scope.row.roleId !== 1">{{ scope.row.roleName }}</el-tag>
            <el-tag type="danger" v-if="scope.row.roleId == 1">{{ scope.row.roleName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最后登陆时间" prop="lastLoginTime" align="center"></el-table-column>
        <el-table-column v-if="actions.includes('2')" type="primary" label="状态" align="center">
            <template slot-scope='scope' >
                <el-switch v-model="scope.row.enabled" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949" active-text="正常" inactive-text="禁用"
                @change="changeStatus($event, scope.row)"></el-switch>
            </template>
        </el-table-column>
        <el-table-column v-if="this.actions.includes('2') || this.actions.includes('3')" label="操作" prop="username" align="center">
            <template slot-scope='scope'>
                <el-button v-if="actions.includes('2')" type="primary" icon="el-icon-edit" @click="openDiog($event, scope.row)"></el-button>
                <el-button v-if="actions.includes('3')" type="danger" icon="el-icon-delete" @click="delButtn(scope.row.userId, scope.row.username)"></el-button>
            </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="this.queryInfo.page"
      :page-sizes="[1, 2, 5, 10, 20]"
      :page-size="this.queryInfo.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="this.totalNum">
    </el-pagination>
    </el-card>
    <!-- 修改用户 -->
    <el-dialog title="用户修改" :visible.sync="dialogFormVisible" width="30%" @close="closeUpate()">
      <el-form :model="updateForm" :rules="addUserFormRule" ref="ruleForm" label-width="100px" >
      <el-form-item prop="loginName" label="登录名">
      <el-input v-model="updateForm.loginName"></el-input>
      </el-form-item>
      <el-form-item prop="username" label="姓名">
      <el-input v-model="updateForm.username"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
      <el-input v-model="updateForm.email"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" label="电话">
      <el-input v-model="updateForm.mobile"></el-input>
      </el-form-item>
      <el-form-item prop="roleId" label="所属角色">
      <el-select v-model="updateForm.roleId" placeholder="请选择角色">
      <el-option v-for="item in roleList" :label="item.remark" :key="item.roleId" :value="item.roleId">
      </el-option>
      </el-select>
      </el-form-item>
          <el-form-item prop="deptName" label="所属部门">
         <el-button round type="warning" size="medium" @click="dialogMenuVisible = true">{{ updateForm.deptName }}</el-button>
      </el-form-item>
       </el-form>
    <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="updateUaser()">修 改</el-button>
  </div>
</el-dialog>
    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="dialogAddFormVisible" width="30%" @close="addUserClose()">
      <el-form :model="updateForm" :rules="addUserFormRule" ref="ruleFormRef" label-width="100px" >
      <el-form-item prop="loginName" label="登录名">
      <el-input v-model="updateForm.loginName"></el-input>
      </el-form-item>
      <el-form-item prop="username" label="姓名">
      <el-input v-model="updateForm.username"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
      <el-input v-model="updateForm.email"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" label="电话">
      <el-input v-model="updateForm.mobile"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
      <el-input type="password" v-model="updateForm.password"></el-input>
      </el-form-item>
      <el-form-item prop="roleId" label="所属角色">
      <el-select v-model="updateForm.roleId" placeholder="请选择角色">
      <el-option v-for="item in roleList" :label="item.remark" :key="item.roleId" :value="item.roleId">
      </el-option>
      </el-select>
      </el-form-item>
       <el-form-item prop="deptName" label="所属部门">
         <el-button type="warning" size="medium" round @click="dialogMenuVisible = true">{{ updateForm.deptName }}</el-button>
      </el-form-item>
       </el-form>
    <div slot="footer" class="dialog-footer">
    <el-button @click="dialogAddFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUserForm()">添 加</el-button>
  </div>
</el-dialog>
<!-- 树型组件 -->
<el-dialog
  :center="true"
  title="组织分配"
  @open="deptDailogOpen"
  :visible.sync="dialogMenuVisible"
  width="20%" >
  <el-tree :data="this.deptList"
  ref="treeRef"
  show-checkbox
  node-key="deptId"
  default-expand-all
  :props="deptListProps" @check="checkTree"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogMenuVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogMenuVisible = false">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import { isNumAndAlp, isEmail, isMobile } from '@/utils/validate'
export default {
  data () {
     var checkLoginName = (rule,value,callback) => {
         if(!value){
         return callback(new Error('不能为空'));
       }
       if(value.length > 16){
         return callback(new Error('登录名不能超过16位'));
       }
        if(!isNumAndAlp(value)){
           return callback(new Error('登录名只能是字母和数字'));
        }
        callback();
      }
     var checkEmail = (rule,value,callback) => {
          if(!value){
         return callback(new Error('不能为空'));
       }
        if(!isEmail(value)){
           return callback(new Error('请输入正确的邮箱号'));
        }
        callback();
      }
       var checkMoible = (rule,value,callback) => {
            if(!value){
         return callback(new Error('不能为空'));
       }
        if(!isMobile(value)){
           return callback(new Error('请输入正确的手机号'));
        }
        callback();
      }
          var checkPassword = (rule,value,callback) => {
               if(!value){
         return callback(new Error('不能为空'));
       }
        if (value.length > 10) {
          return callback(new Error('密码长度为6-10位'));
        }
        if(!isNumAndAlp(value)){
           return callback(new Error('密码只能是字母和数字'));
        }
        callback();
      }
    return {
      // 该页面的操作权限
      actions: this.$store.getters.actions['/userList'],
      userList: {},
      queryInfo: {
        page: 1,
        limit: 20,
        searchType: '',
        keyWords: ''
      },
      totalNum: 100,
      dialogFormVisible: false,
      dialogAddFormVisible: false,
      dialogMenuVisible: false,
      updateForm: {
        deptName: '请选择部门'
      },
      roleList: [],
      searchInput: '',
      select: 'username',
      deptList: [],
      deptListProps: {
        label: 'name',
        children: 'children'
      },
      addUserFormRule: {
        loginName: [{ required: true, trigger: 'blur', validator: checkLoginName }],
        username: [{ required: true, trigger: 'blur', message: '请输入姓名'}],
        email: [{ required: true, trigger: 'blur', validator: checkEmail }],
        mobile: [{ required: true, trigger: 'blur', validator: checkMoible }],
        password: [{ required: true, trigger: 'blur', validator: checkPassword }],
        roleId: [{ required: true, trigger: 'blur', message: '请选择角色' }],
        deptName: [{ required: true, trigger: 'blur', message: '请选择部门' }]
      }

    }
  },
  created () {
    this.getUserList()
    // console.log(this.$store.getters.routers)
  },
  methods: {
    getUserList () {
      this.$api.user.getList(this.queryInfo).then(res => {
        this.userList = res.data
        this.totalNum = res.data.count
      })
    },
    changeStatus (event, data) {
      this.$api.user.updateUser(data).then(res => {
        if (res.code === 200) {
          this.$message.success('修改成功')
        }
      })
    },
    handleSizeChange (newSize) {
      this.queryInfo.limit = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.page = newPage
      this.getUserList()
    },
    openDiog (event, data) {
      this.updateForm = JSON.parse(JSON.stringify(data));
      // this.updateForm = data
      // 查询角色列表
      this.$api.role.getRoleList({
        page: 1,
        limit: 100
      }).then(res => {
        this.roleList = JSON.parse(JSON.stringify(res.data.data));
        // this.roleList = res.data.data
        this.dialogFormVisible = !this.dialogFormVisible
        //this.$refs.treeRef.setCheckedKeys([data.deptId])
      })
    },
    updateUaser () {
      this.$refs.ruleForm.validate(res => {
        if(res){
   this.$api.user.updateUser(this.updateForm).then(res => {
        if (res.code === 200) {
          this.getUserList()
          this.$message.success('修改成功')
          this.dialogFormVisible = false
        }
      })
        }
      })
  
    },
    delUser (Id) {
      this.$api.user.delUser(Id).then(res => {
        this.getUserList()
        this.$message.success('删除成功')
      })
    },
    delButtn (Id, name) {
      this.$confirm('此操作将永久删除用户 ' + name + ' , 是否继续?', '删除提示', {
        confirmButtonText: '让他GG',
        cancelButtonText: '留他狗命',
        type: 'warning'
      }).then(() => {
        this.delUser(Id)
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    searchBtn (){
      this.queryInfo.searchType = this.select
      this.queryInfo.keyWords = this.searchInput
      this.getUserList()     
    },
    deptDailogOpen() {
      if(this.updateForm.deptId){
        this.$refs.treeRef.setCheckedKeys([this.updateForm.deptId])
      } else {
        this.$refs.treeRef.setCheckedKeys([])
      }
        this.$api.dept.getDeptList().then(res => {
        this.deptList = JSON.parse(JSON.stringify(res.data))
      })
    },
    addUser () {
      this.dialogAddFormVisible = !this.dialogAddFormVisible
      this.$api.role.getRoleList(this.queryInfo).then(res => {
      this.roleList = JSON.parse(JSON.stringify(res.data.data))
      })
      this.getDeptList()
      this.$refs.ruleFormRef.resetFields();
    },
    addUserForm (){
      this.$refs.ruleFormRef.validate(res => {
        if(res) {
      this.$api.user.addUser(this.updateForm).then(res => {
        if (res.code === 200) {
          this.$message.success('添加成功')
          this.dialogAddFormVisible = !this.dialogAddFormVisible
          this.getUserList()
        } else {
          this.$message.info(res.message)
        }
      })
        }
      })
    },
    getDeptList () {
      this.$api.dept.getDeptList().then(res => {
        this.deptList = res.data
      })
    },
    checkTree (data){
      this.$refs.treeRef.setCheckedKeys([data.deptId])
      this.updateForm.deptId = data.deptId
      this.updateForm.deptName = data.name
      console.log(this.updateForm)
      console.log(data.deptId)
    },
    addUserClose () {
      this.updateForm = {}
    },
    closeUpate () {
      this.updateForm = {}
    }
  }
}
</script>
<style lang="less" scoped>
.selectType {
    width: 100px;
  }
 .input-with-select {
   width: 400px;
   padding-top: 10px;
   padding-bottom: 20px;
   padding-right: 20px;
   > el-select {
    width: 120px;
  }
 }
</style>
